package cn.ycc1.boot3task.task;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author ycc
 * @date 2025/10/28
 */
@Component
public class EmailTask {

    private static final DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 模拟发送邮件 - 异步执行
     */
    @Async("taskExecutor")
    public void sendEmail(String to, String subject, String content) {
        String startTime = LocalDateTime.now().format(formatter);
        System.out.println(Thread.currentThread().getName() +
                " - 开始发送邮件 [" + startTime + "] -> " + to);

        try {
            // 模拟邮件发送耗时 3-8 秒
            int processTime = 3000 + (int)(Math.random() * 5000);
            Thread.sleep(processTime);

            String endTime = LocalDateTime.now().format(formatter);
            System.out.println(Thread.currentThread().getName() +
                    " - 邮件发送完成 [" + endTime + "] -> " + to +
                    " 耗时: " + processTime + "ms");

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("邮件发送被中断: " + e.getMessage());
        }
    }

    /**
     * 模拟数据处理任务
     */
    @Async("taskExecutor")
    public void processData(int batchId) {
        String startTime = LocalDateTime.now().format(formatter);
        System.out.println(Thread.currentThread().getName() +
                " - 开始处理数据批次 [" + startTime + "] -> " + batchId);

        try {
            // 模拟数据处理耗时 2-5 秒
            int processTime = 2000 + (int)(Math.random() * 3000);
            Thread.sleep(processTime);

            String endTime = LocalDateTime.now().format(formatter);
            System.out.println(Thread.currentThread().getName() +
                    " - 数据处理完成 [" + endTime + "] -> " + batchId +
                    " 耗时: " + processTime + "ms");

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("数据处理被中断: " + e.getMessage());
        }
    }
}
